package development.app.mxh;

import iplayparticle.view.iplayparticleResources;

import java.util.Vector;

import particle.core.platform.IPlatformPictureImportEventHandler;
import particle.core.platform.Platform;
import particle.core.platform.PlatformPictureImportEvent;
import particle.core.tools.ByteBuffer;
import particle.core.view.assets.Image;
import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.TimerListener;
import state.component.BottomBar;
import state.component.Checkbox;
import state.component.Event;
import state.component.EventListener;
import state.component.GameMenu;
import state.component.GameScrollBar;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.ByteArray;
import state.util.array.CheckBoxArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.FrmDownloadResource;
import development.Global;
import development.bean.Comment;
import development.group.FrmGroup18Plus;
import development.group.FrmGroupKetBanMangXHChat;
import development.group.FrmGroupMenu;
import development.socket.SocketClientUtil;

public class FrmWall extends GameForm implements EventListener, TimerListener, IPlatformPictureImportEventHandler {
  public static final int CHECK_PERMISSION_REQUEST = 620;
  public static final int PERMISSION_SUCCESS_RESPONSE = 621;
  public static final int PERMISSION_FAIL_RESPONSE = 622;

  public static final int LIST_COMMENT_REQUEST = 623;
  public static final int LIST_COMMENT_RESPONSE = 624;

  public static final int COMMENT_REQUEST = 625;
  public static final int COMMENT_RESPONSE = 626;

  public static final int COMMENT_DETAIL_REQUEST = 627;
  public static final int COMMENT_DETAIL_RESPONSE = 628;

  public static final int LIKE_COMMENT_REQUEST = 629;
  public static final int LIKE_COMMENT_RESPONSE = 630;

  public static final int DELETE_COMMENT_REQUEST = 631;
  public static final int DELETE_COMMENT_RESPONSE = 632;

  public static final int CHANGE_ROLE_REQUEST = 633;

  private static GameForm singleton;
  private ImageText text8;
  private String type;
  private int dy;

  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView;

  private int packageNumber;
  private int totalPackage;
  private int percent;

  private GameMenu menuComment;
  private GameMenu menuCommentUserComment;
  private boolean isShowChangeRole;
  private int roleIndex;
  private CheckBoxArray cbRole;

  private GameImage likeImage;

  private int commentIndex;
  private int commentStart;
  private int commentEnd;

  public static final int MY_WALL_TYPE = 0;
  public static final int YOUR_WALL_TYPE = 1;
  private int WALL_TYPE = MY_WALL_TYPE;

  private TextField txtComment;
  private Sprite commentButtonSprite;
  private Sprite addImageButtonSprite;
  private GameImage buttonImage;

  private Hashtable _parameters;
  private Vector comments;
  private GameImage commentImageDetail;
  private String ofUser;
  private int currentX;

  private ByteArray attachByteArray;
  private GameImage attachIcon;

  private GameImage[] arrowImage;

  private int VIEW_COMMENT_IMAGE_DY;
  private int VIEW_COMMENT_IMAGE_DX;

  private int commentUserCommentIndex;
  public static GameForm backForm;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmWall();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    this._parameters = parameters;

    comments = new Vector();
    commentIndex = -2;
    commentStart = 0;
    commentEnd = 5;
    type = "list_comment";
    currentX = Global.getDefaultAvatar().getWidth() + 5;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    dy = DrawUtils.getTopBarHeight();
    VIEW_COMMENT_IMAGE_DX = 0;
    VIEW_COMMENT_IMAGE_DY = dy;
    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10);
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    txtComment = new TextField(_manager, TextField.CONSTRAINT_ANY, null);
    txtComment.setAnchor(GameConstants.BOTTOM_LEFT_ANCHOR);
    txtComment.setVisible(true);
    buttonImage = new GameImage(iplayparticleResources.image_button, null, null);
    commentButtonSprite = new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR);
    commentButtonSprite.setImage(buttonImage);
    commentButtonSprite.setAnchor(Constants.TOP_LEFT_ANCHOR);
    commentButtonSprite.setVisible(false);
    commentButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        text8.drawString2(g, "Gửi", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
      }
    });
    addImageButtonSprite = new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR);
    addImageButtonSprite.setImage(buttonImage);
    addImageButtonSprite.setAnchor(Constants.TOP_LEFT_ANCHOR);
    addImageButtonSprite.setVisible(false);
    addImageButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        text8.drawString2(g, "Gắn ảnh", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
      }
    });
    cbRole = CheckBoxArray.create(3);
    String[] cbName = new String[] { "Chỉ mình tôi", "Bạn bè của tôi", "Tất cả mọi người" };
    for (int i = 0; i < cbRole.len(); i++) {
      Checkbox cb = new Checkbox(_manager, this, Constants.CHECK_BOX_STYLE_APP, 0, 0);
      cb.setLabel(cbName[i]);
      cb.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
      cb.setVisible(false);
      cbRole.set(i, cb);
    }
    cbRole.array[2].setChecked(true);

    likeImage = ImageUtil.getImage(Constants.MANGXH_CATEGORY, "like_icon.png");
    attachIcon = ImageUtil.getImage(Constants.MANGXH_CATEGORY, "dinhkem.png");

    arrowImage = new GameImage[4];
    // trai
    arrowImage[0] = ImageUtil.getImage(Constants.MANGXH_CATEGORY, "arrow.png");
    // tren
    arrowImage[1] = ImageUtil.rotate(arrowImage[0], 90);
    // phai
    arrowImage[2] = ImageUtil.rotate(arrowImage[0], 180);
    // duoi
    arrowImage[3] = ImageUtil.rotate(arrowImage[0], 270);

    WALL_TYPE = NumberUtil.parseInt(parameters.get("wallType").toString());
    ofUser = (String) parameters.get("User");
    if (ofUser == null || ofUser.equals("")) {
      ofUser = Global.currentUser.getName();
    }
    if (ofUser.equals(Global.currentUser.getName())) {
      WALL_TYPE = MY_WALL_TYPE;
    }
    // Create bottom bar
    if (WALL_TYPE == MY_WALL_TYPE) {
      menuComment = new GameMenu(null, new String[] { "Quyền xem & viết", "Xem tường", "Thích", "Tài khoản", "Kết bạn", "Xóa lời bình", "Menu MXH" }, 7, this, Constants.MENU_STYLE, 0,
          GameConstants.SCREEN_HEIGHT - 45);
    } else {
      menuComment = new GameMenu(null, new String[] { "Thích", "Tài khoản", "Xem tường", "Kết bạn", "Menu MXH" }, 5, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    }
    menuCommentUserComment = new GameMenu(null, new String[] { "Xem ảnh", "Menu MXH" }, 2, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    BottomBar bottomBar = DrawUtils.getBottomBar(_manager);
    bottomBar.setLabels("Menu", "Chọn", "");
    bottomBar.setLeftMenu("Menu", menuComment);
    _manager.enableTouchPad();

    DataPackage dataPackage = DataPackage.createDataPackage1(LIST_COMMENT_REQUEST);
    dataPackage.putString(ofUser);
    dataPackage.putInt(commentStart);
    dataPackage.putInt(commentEnd);
    Global.appClient.write(dataPackage);
    comments.removeAllElements();
    setTimerListener(this);
    new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR).setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        DrawUtils.drawTopBar(g);
        if (type.equals("comment_image")) {
          text8.drawString2(g, "Xem ảnh", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
        }
        if (type.equals("list_comment")) {
          if (!comments.isEmpty()) {
            Comment comment = (Comment) comments.elementAt(0);
            text8.drawString2(g, comment.userMaster, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
          } else {
            text8.drawString2(g, Global.currentUser.getName(), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
          }
        }
      }
    }).setSize(Constants.SCREEN_WIDTH, 25);
    commentUserCommentIndex = 0;
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (type.equals("list_comment")) {
      drawComment(g);
    }
    if (isShowChangeRole) {
      drawChangeRole(g);
    }
    if (type.equals("commentUserComment")) {
      if (comments != null && !comments.isEmpty()) {
        drawCommentUserComment(g);
      }
    }
    if (type.equals("comment_image")) {
      drawCommentImage(g);
    }
    DrawUtils.drawTopBar(g);
    drawMenu(g);
  }

  private void drawCommentUserComment(Graphics g) {
    Comment comment = (Comment) comments.elementAt(commentIndex);
    int commentDy = dy;
    GameImage avatar = Global.getAvatar(comment.userComment);
    g.drawImage(avatar, 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
    text8.setBold(true);
    text8.drawString3(g, comment.userComment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
    if (comment.like > 0) {
      g.drawImage(likeImage, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2, commentDy, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString3(g, String.valueOf(comment.like), GameColor.YELLOW_CODE, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2 + likeImage.getWidth() + 2, commentDy,
          GameConstants.TOP_LEFT_ANCHOR, scrollBar);
    }
    text8.setBold(false);
    commentDy = commentDy + 15;
    if (text8.stringWidth(comment.comment) > GameConstants.SCREEN_WIDTH - Global.getDefaultAvatar().getWidth() + 5) {
      text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, currentX, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      g.drawImage(avatar, 0, commentDy - 15, GameConstants.TOP_LEFT_ANCHOR);
    } else {
      text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
    }
    commentDy = commentDy + 10;
    if (comment.image != null) {
      commentDy = commentDy + 15;
      g.drawImage(comment.image, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR);
      commentDy = commentDy + Global.getDefaultAvatar().getHeight();
    }
    text8.drawString3(g, "[" + comment.created + "]", GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
    commentDy = commentDy + 15;

    g.setColor(0xC0C0C0);
    g.drawLine(0, commentDy + 5, GameConstants.SCREEN_WIDTH, commentDy + 5);
    commentDy = commentDy + 7;

    g.drawImage(Global.getAvatar(Global.currentUser.getName()), 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setSize(GameConstants.SCREEN_WIDTH - 65, text8.getHeight() * 2);
    txtComment.setPosition(Global.getDefaultAvatar().getWidth() + DEFAULT_TEXT_X, commentDy);
    commentDy = commentDy + txtComment.getHeight() + 7;
    commentButtonSprite.setPosition(GameConstants.SCREEN_WIDTH - 85, commentDy);
    commentButtonSprite.setVisible(true);
  }

  private void drawCommentImage(Graphics g) {
    g.drawImage(commentImageDetail, VIEW_COMMENT_IMAGE_DX, VIEW_COMMENT_IMAGE_DY, GameConstants.TOP_LEFT_ANCHOR);
    g.drawImage(arrowImage[0], 0, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_LEFT_ANCHOR);
    g.drawImage(arrowImage[1], GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_LEFT_ANCHOR);
    g.drawImage(arrowImage[2], GameConstants.SCREEN_WIDTH, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_RIGHT_ANCHOR);
    g.drawImage(arrowImage[3], GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight(), GameConstants.BOTTOM_LEFT_ANCHOR);
  }

  private void drawComment(Graphics g) {
    int commentDy = dy + 5;
    text8.drawString2(g, "Bạn đang nghĩ gì?", GameColor.YELLOW_CODE, Global.getDefaultAvatar().getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR);
    commentDy += 20;
    g.drawImage(Global.getAvatar(Global.currentUser.getName()), 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
    txtComment.setSize(GameConstants.SCREEN_WIDTH - 65, text8.getHeight() * 2);
    txtComment.setPosition(Global.getDefaultAvatar().getWidth() + DEFAULT_TEXT_X, commentDy);
    commentDy = commentDy + txtComment.getHeight() + 7;
    addImageButtonSprite.setPosition(txtComment.getRealX(), commentDy);
    addImageButtonSprite.setVisible(true);
    if (attachByteArray != null) {
      g.drawImage(attachIcon, addImageButtonSprite.getRealX() + addImageButtonSprite.getWidth() + 2, addImageButtonSprite.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
    }
    commentButtonSprite.setPosition(GameConstants.SCREEN_WIDTH - 85, commentDy);
    commentButtonSprite.setVisible(true);
    commentDy = commentDy + 30;
    for (int i = 0; i < comments.size(); i++) {
      Comment comment = (Comment) comments.elementAt(i);
      g.setColor(0xC0C0C0);
      g.drawLine(0, commentDy, GameConstants.SCREEN_WIDTH, commentDy);
      if (commentIndex == i) {
        g.setColor(0x53A4CF);
        if (comment.image == null) {
          g.fillRect(0, commentDy, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight());
        } else {
          g.fillRect(0, commentDy, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight() * 2 + 10);
        }
      }
      GameImage avatar = Global.getAvatar(comment.userComment);
      g.drawImage(avatar, 0, commentDy, GameConstants.TOP_LEFT_ANCHOR);
      
      // TODO: không nên split trong hàm vẽ
      StringArray arrComment = GameStringUtils.split(comment.comment, ">>");
      if (arrComment != null && arrComment.len() == 2) {
        text8.drawString3(g, comment.userComment + ">>" + arrComment.get(0), GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      } else {
        text8.drawString3(g, comment.userComment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      }
      text8.setBold(true);
      if (comment.like > 0) {
        g.drawImage(likeImage, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2, commentDy, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString3(g, String.valueOf(comment.like), GameColor.YELLOW_CODE, avatar.getWidth() + 5 + text8.stringWidth(comment.userComment) + 2 + likeImage.getWidth() + 2, commentDy,
            GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      }
      text8.setBold(false);
      commentDy = commentDy + 15;
      if (commentIndex == i) {
        if (arrComment.len() == 2) {
          if (text8.stringWidth(arrComment.get(1)) > GameConstants.SCREEN_WIDTH - Global.getDefaultAvatar().getWidth() + 5) {
            text8.drawString3(g, arrComment.get(1), GameColor.WHITE_CODE, currentX, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            g.drawImage(avatar, 0, commentDy - 15, GameConstants.TOP_LEFT_ANCHOR);
          } else {
            text8.drawString3(g, arrComment.get(1), GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
        } else {
          if (text8.stringWidth(comment.comment) > GameConstants.SCREEN_WIDTH - Global.getDefaultAvatar().getWidth() + 5) {
            text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, currentX, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            g.drawImage(avatar, 0, commentDy - 15, GameConstants.TOP_LEFT_ANCHOR);
          } else {
            text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
        }
      } else {
        text8.drawString3(g, comment.comment, GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      }
      commentDy = commentDy + 10;
      if (comment.image != null) {
        commentDy = commentDy + 15;
        g.drawImage(comment.image, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR);
        commentDy = commentDy + Global.getDefaultAvatar().getHeight();
      }
      text8.drawString3(g, "[" + comment.created + "]", GameColor.WHITE_CODE, avatar.getWidth() + 5, commentDy, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      commentDy = commentDy + 15;

      g.setColor(0xC0C0C0);
      g.drawLine(0, commentDy + 5, GameConstants.SCREEN_WIDTH, commentDy + 5);
      commentDy = commentDy + 7;
    }
    scrollBar.draw(g);
  }

  private void drawChangeRole(Graphics g) {
    dy = DrawUtils.getTopBarHeight();
    text8.drawString2(g, "Quyền xem tường của bạn", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 0, GameConstants.TOP_HCENTER_ANCHOR);
    int textY = dy;
    textY = text8.drawParagraph2(g, "Những ai có quyền xem và bình luận:", GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH, DEFAULT_TEXT_X, textY, scrollBar);
    textY = textY + 5;
    for (int i = 0; i < cbRole.len(); i++) {
      if (roleIndex == i) {
        cbRole.array[i].setFocused(true);
      } else {
        cbRole.array[i].setFocused(false);
      }
      cbRole.array[i].setVisible(true);
      cbRole.array[i].setPosition(DEFAULT_TEXT_X, textY);
      cbRole.array[i].draw(g);
      textY = textY + 20;
    }
  }

  private void drawMenu(Graphics g) {
    if (percent > 0 && percent < 100) {
      DrawUtils.getBottomBar(_manager).setCenterLabel(percent + "%");
    }
    if (type.equals("list_comment")) {
      for (int i = 0; i < comments.size(); i++) {
        Comment comment = (Comment) comments.elementAt(i);
        if (comment.image != null) {
          DrawUtils.getBottomBar(_manager).setCenterLabel("Xem ảnh");
        } else {
          DrawUtils.getBottomBar(_manager).setCenterLabel("");
        }
        DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
      }
    }
    if (isShowChangeRole) {
      DrawUtils.getBottomBar(_manager).setLabels("", "Chọn", "Trở về");
    }
    if (type.equals("comment_image")) {
      DrawUtils.getBottomBar(_manager).setLabels("", "", "Trở về");
    }
    if (type.equals("list_comment")) {
      DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuComment);
    } else if (type.equals("commentUserComment")) {
      DrawUtils.getBottomBar(_manager).setLeftMenu("Menu", menuCommentUserComment);
    } else {
      DrawUtils.getBottomBar(_manager).setLeftMenu("", null);
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    type = mapDataPackage.popString("type");
    switch (header) {
    case LIST_COMMENT_RESPONSE:
      Global.systemCanvas.hideAlert();
      txtComment.clearText();
      txtComment.setVisible(true);
      Comment comment = new Comment();
      comment.masterId = mapDataPackage.getString("master_id");
      comment.userMaster = mapDataPackage.getString("user_master");
      comment.comment = mapDataPackage.getString("message");
      comment.created = mapDataPackage.getString("created");
      comment.id = mapDataPackage.getString("comment_id");
      comment.userComment = mapDataPackage.getString("user_comment");
      comment.like = NumberUtil.parseInt(mapDataPackage.getString("total_like"));
      comment.totalComment = mapDataPackage.getInt("total_comment");
      ByteArray btImage = mapDataPackage.getByteArray("image");
      if (btImage != null) {
        comment.image = GameImage.createImage(btImage, 0, btImage.len());
      }
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      if (comment.masterId != null && !comment.masterId.equals("")) {
        comments.addElement(comment);
      }
      if (!comments.isEmpty()) {
        commentIndex = 0;
      } else {
        commentIndex = -3;
      }
      break;
    case LIKE_COMMENT_RESPONSE:
      Global.systemCanvas.hideAlert();
      int errorCode = mapDataPackage.getInt("errorCode");
      if (errorCode == -1) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn đã like lời bình này rồi");
        return;
      }
      comment = (Comment) comments.elementAt(commentIndex);
      if (comment != null) {
        comment.like = mapDataPackage.getInt("like");
      }
      break;
    case DELETE_COMMENT_RESPONSE:
      Global.systemCanvas.hideAlert();
      comments.removeElementAt(commentIndex);
      commentIndex = 0;
      break;
    case COMMENT_DETAIL_RESPONSE:
      Global.systemCanvas.hideAlert();
      btImage = mapDataPackage.getByteArray("image");
      if (btImage == null) {
        commentImageDetail = Global.getDefaultAvatar();
      } else {
        commentImageDetail = GameImage.createImage(btImage, 0, btImage.len());
      }
      txtComment.setVisible(false);
      commentButtonSprite.setVisible(false);
      addImageButtonSprite.setVisible(false);
      break;
    default:
      break;
    }
  }

  private void goBack() {
    if (backForm != null) {
      Global.nextState(backForm, _parameters);
      if (backForm instanceof FrmGroup18Plus) {
        FrmGroup18Plus.setTab(1);
      } else if (backForm instanceof FrmGroupKetBanMangXHChat) {
        FrmGroupKetBanMangXHChat.setTab(1);
      }
    } else {
      if (Global.systemCanvas.lastState instanceof FrmDownloadResource) {
        GameGlobal.nextState(FrmGroupMenu.instance(), _parameters);
      } else {
        GameGlobal.nextState(Global.systemCanvas.lastState, _parameters);
      }
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.RIGHT:
      if (type.equals("comment_image")) {
        VIEW_COMMENT_IMAGE_DX = VIEW_COMMENT_IMAGE_DX - 10;
      }
      if (type.equals("list_comment")) {
        Comment comment = (Comment) comments.elementAt(0);
        if (commentEnd >= comment.totalComment) {
          return;
        }
        if ((commentEnd + 5) > comment.totalComment) {
          commentEnd = comment.totalComment;
          commentStart = commentEnd - 5;
        } else {
          commentStart += 5;
          commentEnd += 5;
        }
        DataPackage dataPackage = DataPackage.createDataPackage1(LIST_COMMENT_REQUEST);
        dataPackage.putString(ofUser);
        dataPackage.putInt(commentStart);
        dataPackage.putInt(commentEnd);
        Global.appClient.write(dataPackage);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        commentIndex = 0;
        comments.removeAllElements();
        dy = DrawUtils.getTopBarHeight();
      }
      break;
    case Key.LEFT:
      if (type.equals("comment_image")) {
        VIEW_COMMENT_IMAGE_DX = VIEW_COMMENT_IMAGE_DX + 10;
      }
      if (type.equals("list_comment")) {
        if (commentStart <= 0) {
          return;
        }
        commentStart -= 5;
        commentEnd -= 5;
        if (commentStart < 0) {
          commentStart = 0;
          commentEnd = 5;
        }
        DataPackage dataPackage = DataPackage.createDataPackage1(LIST_COMMENT_REQUEST);
        dataPackage.putString(ofUser);
        dataPackage.putInt(commentStart);
        dataPackage.putInt(commentEnd);
        Global.appClient.write(dataPackage);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        commentIndex = 0;
        comments.removeAllElements();
        dy = DrawUtils.getTopBarHeight();
      }
      break;
    case Key.SOFT_RIGHT:
      if (isShowChangeRole) {
        for (int i = 0; i < cbRole.len(); i++) {
          cbRole.array[i].setVisible(false);
        }
        isShowChangeRole = false;
        type = "list_comment";
        txtComment.setVisible(true);
        commentButtonSprite.setVisible(true);
        dy = DrawUtils.getTopBarHeight();
        return;
      }
      if (type.equals("list_comment")) {
        goBack();
        return;
      }
      if (type.equals("commentUserComment")) {
        type = "list_comment";
        commentUserCommentIndex = 0;
        txtComment.setFocused(false);
        commentIndex = 0;
        dy = DrawUtils.getTopBarHeight() + 5;
      }
      if (type.equals("comment_image")) {
        type = "commentUserComment";
        commentImageDetail = null;
        txtComment.setVisible(true);
        txtComment.setFocused(true);
      }
      break;
    case Key.DOWN:
      if (type.equals("commentUserComment")) {
        if (commentUserCommentIndex < 1) {
          commentUserCommentIndex++;
        }
        if (commentUserCommentIndex == 1) {
          txtComment.setFocused(false);
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gửi", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
      }
      if (type.equals("comment_image")) {
        VIEW_COMMENT_IMAGE_DY = VIEW_COMMENT_IMAGE_DY - 10;
      }
      if (isShowChangeRole) {
        if (roleIndex < cbRole.len() - 1) {
          roleIndex++;
        }
      }
      if (type.equals("list_comment")) {
        if (commentIndex < comments.size() - 1) {
          commentIndex++;
        }
        if (commentIndex == -1) {
          txtComment.setFocused(false);
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gửi", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
          addImageButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gắn ảnh", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else if (commentIndex == -2) {
          txtComment.setFocused(false);
          addImageButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gắn ảnh", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gửi", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else if (commentIndex == -3) {
          txtComment.setFocused(true);
          addImageButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gắn ảnh", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gửi", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else {
          if (commentIndex < comments.size() - 1) {
            Comment comment = (Comment) comments.elementAt(commentIndex);
            if (comment.image == null) {
              dy -= Global.getDefaultAvatar().getHeight();
            } else {
              dy -= Global.getDefaultAvatar().getHeight() * 2 + 50;
            }
          }
        }
        if (commentIndex == 0 || commentIndex == -1 || commentIndex == -2 || commentIndex == -3) {
          dy = DrawUtils.getTopBarHeight() + 5;
        }
      }
      break;
    case Key.UP:
      if (type.equals("commentUserComment")) {
        if (commentUserCommentIndex > 0) {
          commentUserCommentIndex--;
        }
        if (commentUserCommentIndex == 1) {
          txtComment.setFocused(false);
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gửi", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else {
          txtComment.setFocused(true);
          commentButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Gửi", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
      }
      if (type.equals("comment_image")) {
        VIEW_COMMENT_IMAGE_DY = VIEW_COMMENT_IMAGE_DY + 10;
      }
      if (isShowChangeRole) {
        if (roleIndex > 0) {
          roleIndex--;
        }
      }
      if (type.equals("list_comment")) {
        if (commentIndex > -3) {
          commentIndex--;
          if (commentIndex == -1) {
            txtComment.setFocused(false);
            commentButtonSprite.setDrawListener(new DrawListener() {
              public void paint(Sprite source, Graphics g) {
                text8.drawString2(g, "Gửi", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
              }
            });
            addImageButtonSprite.setDrawListener(new DrawListener() {
              public void paint(Sprite source, Graphics g) {
                text8.drawString2(g, "Gắn ảnh", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
              }
            });
          } else if (commentIndex == -2) {
            txtComment.setFocused(false);
            commentButtonSprite.setDrawListener(new DrawListener() {
              public void paint(Sprite source, Graphics g) {
                text8.drawString2(g, "Gửi", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
              }
            });
            addImageButtonSprite.setDrawListener(new DrawListener() {
              public void paint(Sprite source, Graphics g) {
                text8.drawString2(g, "Gắn ảnh", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
              }
            });
          } else if (commentIndex == -3) {
            txtComment.setFocused(true);
            commentButtonSprite.setDrawListener(new DrawListener() {
              public void paint(Sprite source, Graphics g) {
                text8.drawString2(g, "Gửi", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
              }
            });
            addImageButtonSprite.setDrawListener(new DrawListener() {
              public void paint(Sprite source, Graphics g) {
                text8.drawString2(g, "Gắn ảnh", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
              }
            });
          } else {
            if (commentIndex < comments.size() - 1) {
              Comment comment = (Comment) comments.elementAt(commentIndex);
              if (comment.image == null) {
                dy += Global.getDefaultAvatar().getHeight();
              } else {
                dy += Global.getDefaultAvatar().getHeight() * 2 + 62;
              }
            }
            if (commentIndex == comments.size() - 1) {
              dy = textView._y;
            }
          }
          if (commentIndex == 0 || commentIndex == -1 || commentIndex == -2 || commentIndex == -3) {
            dy = DrawUtils.getTopBarHeight() + 5;
          }
        }
      }
      break;
    case Key.FIRE:
      if (txtComment.isFocused()) {
        txtComment.pointerReleased(txtComment, txtComment.getRealX(), txtComment.getRealY());
      }
      if (commentIndex == -1) {
        if (txtComment.getText().length() == 0) {
          Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa viết lời bình");
        } else {
          if (attachByteArray != null) {
            DataPackage dataPackage = DataPackage.createDataPackage3(COMMENT_REQUEST, attachByteArray.len() + 200);
            Comment comment = (Comment) comments.elementAt(0);
            dataPackage.putString(comment.masterId);
            dataPackage.putString(txtComment.getText());
            dataPackage.putString(comment.userMaster);
            dataPackage.putByteArray(attachByteArray);
            Global.appClient.write(dataPackage);
          } else {
            DataPackage dataPackage = DataPackage.createDataPackage1(COMMENT_REQUEST);
            Comment comment = (Comment) comments.elementAt(0);
            dataPackage.putString(comment.masterId);
            dataPackage.putString(txtComment.getText());
            dataPackage.putString(comment.userMaster);
            Global.appClient.write(dataPackage);
          }
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
          comments.removeAllElements();
          attachByteArray = null;
          return;
        }
      }
      if (commentIndex == -2) {
        Global.alert.showAlert1(this, GameAlert.OK_TYPE, StringArray.create1( "Bạn có muốn gắn ảnh", "vào lời bình?" ), 50);
      }
      if (type.equals("list_comment")) {
        if (commentIndex > -1) {
          dy = DrawUtils.getTopBarHeight();
          type = "commentUserComment";
          addImageButtonSprite.setVisible(false);
          txtComment.setFocused(true);
          commentUserCommentIndex = 0;
        }
      }
      if (type.equals("commentUserComment")) {
        if (commentUserCommentIndex == 1) {
          Comment comment = (Comment) comments.elementAt(commentIndex);
          DataPackage dataPackage = DataPackage.createDataPackage1(COMMENT_REQUEST);
          dataPackage.putString(comment.masterId);
          dataPackage.putString(comment.userComment + ">>" + txtComment.getText());
          dataPackage.putString(comment.userMaster);
          Global.appClient.write(dataPackage);
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
          commentUserCommentIndex = 0;
          comments.removeAllElements();
        }
      }
      if (isShowChangeRole) {
        if (cbRole.array[roleIndex].isChecked()) {
          return;
        }
        for (int i = 0; i < cbRole.len(); i++) {
          cbRole.array[i].setChecked(false);
        }
        cbRole.array[roleIndex].setChecked(true);
        DataPackage dataPackage = DataPackage.createDataPackage1(CHANGE_ROLE_REQUEST);
        Comment comment = (Comment) comments.elementAt(0);
        dataPackage.putString(comment.masterId);
        dataPackage.putString(cbRole.array[roleIndex].getLabel());
        Global.appClient.write(dataPackage);
      }
      break;
    default:
      if (txtComment.isFocused()) {
        txtComment.keyReleased1(keyCode);
      }
      break;
    }
  }

  public void onActionPerform(Event event) {
    // "Quyền xem & viết", "Quyền viết", "Thích", "Xem album", "Kết bạn",
    // "Xóa lời bình", "Menu MXH"
    String action = event.getAction();
    DataPackage dataPackage = null;
    if (action.equals("Menu MXH")) {
      goBack();
    } else if (action.equals("Thích")) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      dataPackage = DataPackage.createDataPackage1(LIKE_COMMENT_REQUEST);
      dataPackage.putString(comment.id);
      Global.appClient.write(dataPackage);
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
    } else if (action.equals("Xóa lời bình")) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      dataPackage = DataPackage.createDataPackage1(DELETE_COMMENT_REQUEST);
      dataPackage.putString(comment.id);
      Global.appClient.write(dataPackage);
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
    } else if (action.equals("Quyền xem & viết")) {
      type = "";
      txtComment.setVisible(false);
      commentButtonSprite.setVisible(false);
      isShowChangeRole = true;
    } else if (action.equals("Xem album")) {
      _parameters = new Hashtable();
      _parameters.put("albumType", new Integer(FrmMyAlbum.YOUR_ALBUM_TYPE));
      Comment comment = (Comment) comments.elementAt(commentIndex);
      _parameters.put("User", comment.userComment);
      FrmMyAlbum.backForm = backForm;
      Global.nextState(FrmMyAlbum.instance(), _parameters);
    } else if (action.equals("Xem tường") && type.equals("list_comment")) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      if (comment.userComment.equals(ofUser)) {
        return;
      }
      _parameters.put("wallType", new Integer(FrmWall.YOUR_WALL_TYPE));
      _parameters.put("User", comment.userComment);
      Global.nextState(FrmWall.instance(), _parameters);
    } else if (action.equals("Tài khoản")) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      _parameters.put("User", comment.userComment);
      FrmAccount.backForm = this;
      Global.nextState(FrmAccount.instance(), _parameters);
    } else if (action.equals("Kết bạn")) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      SocketClientUtil.addFriendRequest(comment.userComment);
    } else if (action.equals("Xem ảnh") && type.equals("commentUserComment")) {
      Comment comment = (Comment) comments.elementAt(commentIndex);
      if (comment.image != null) {
        dataPackage = DataPackage.createDataPackage1(COMMENT_DETAIL_REQUEST);
        dataPackage.putString(comment.id);
        Global.appClient.write(dataPackage);
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
      }
    }
  }
  
  public void onPlatformPictureImport(Platform platform, PlatformPictureImportEvent event) {
    platform.removePictureImportEventHandler(this);
    ByteBuffer byteBuffer = new ByteBuffer();
    event.picture.toBuffer(byteBuffer, Image.FormatPNG);
    ByteArray data = ByteArray.create(byteBuffer.getLength());
    for (int i = 0; i < data.len(); i++) {
      data.set(i, byteBuffer.getByte(i));
    }
    attachByteArray = data;
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 50) {
      Platform platform = Platform.getInstance();
      platform.addPictureImportEventHandler(this);
      platform.startPictureImport();
    }
  }

  public void doTask() {
    Comment comment = (Comment) comments.elementAt(commentIndex);
    if (comment == null) {
      return;
    }
    int strWidth = text8.stringWidth(comment.comment);
    if (currentX + strWidth > 10) {
      currentX -= 2;
    } else {
      currentX = Global.getDefaultAvatar().getWidth() + 5;
    }
  }

  public void destroy() {
    text8 = null;
    type = null;
    scrollBar = null;
    textView = null;

    menuComment = null;
    isShowChangeRole = false;
    cbRole = null;

    likeImage = null;

    txtComment = null;
    commentButtonSprite = null;
    addImageButtonSprite = null;
    buttonImage = null;

    _parameters = null;
    comments = null;
    commentImageDetail = null;
    ofUser = null;

    attachByteArray = null;
    attachIcon = null;
    arrowImage = null;
    menuCommentUserComment = null;
  }
}
